﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using LpbPrj.Client.Users.Dtos;
using System.Collections.Generic;
using System.Data.Entity;
using System.Threading.Tasks;

namespace LpbPrj.Client.Users
{
    public class UserService : ClientAppServiceBase, IUserService
    {
        private readonly IRepository<User, long> _entityRepository;
        public UserService(IRepository<User, long> entityRepository)
        {
            _entityRepository = entityRepository;
        }


        public async Task<UserListDto> GetById(string input)
        {
            var entity = await _entityRepository.GetAll().AsNoTracking().FirstOrDefaultAsync(p => p.UserName.Equals(input));
            return ObjectMapper.Map<UserListDto>(entity);
        }

        public async Task<UserEditDto> GetForEdit(string input)
        {
            UserEditDto editDto = null;

            var entity = await _entityRepository.GetAll().AsNoTracking().FirstOrDefaultAsync(p => p.UserName.Equals(input));
            if (entity == null)
            {
                editDto = new UserEditDto();
            }
            else
            {
                editDto = ObjectMapper.Map<UserEditDto>(entity);
            }

            return editDto;
        }

        public async Task<UserListDto> CreateOrUpdate(UserEditDto input)
        {
            long? id = input.Id;

            if (input.Id.HasValue)
            {
                await Update(input);
            }
            else
            {
                id = await Create(input);
            }
            CurrentUnitOfWork.SaveChanges();
            if (id.HasValue)
            {
                var entity = await _entityRepository.GetAll().AsNoTracking().FirstOrDefaultAsync(p => p.Id == id.Value);
                return ObjectMapper.Map<UserListDto>(entity);
            }

            return null;
        }

        protected virtual async Task<long> Create(UserEditDto input)
        {
            var entity = ObjectMapper.Map<User>(input);
            return await _entityRepository.InsertAndGetIdAsync(entity);
        }

        protected virtual async Task Update(UserEditDto input)
        {
            var entity = await _entityRepository.GetAll().AsNoTracking().FirstOrDefaultAsync(p => p.Id == input.Id.Value);
            ObjectMapper.Map(input, entity);
            await _entityRepository.UpdateAsync(entity);
        }

        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
        }

        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
        }

    }
}
